package com.entor.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class FastJsonHttpMessageConverter extends
		AbstractHttpMessageConverter<Object> {
	
	public final static Charset UTF8 = Charset.forName("UTF-8");
	
	public Charset charset = UTF8;
	
	public SerializerFeature[] serializerFeature;

	@Override
	protected Object readInternal(Class<? extends Object> arg0,
			HttpInputMessage arg1) throws IOException,
			HttpMessageNotReadableException {
		//声明一个流文件
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		InputStream in = arg1.getBody();
		byte[] buf = new byte[1024];
		for(;;){
			int len = in.read(buf);
			if(len == -1){
				break;
			}
			if(len>0){
				baos.write(buf, 0, len);
			}
		}
		/*int len = 0;
		while((len = in.read(buf))==-1){
			baos.write(buf, 0, len);
		}*/
		//声明一个字节数组
		byte[] bytes = baos.toByteArray();
		if(charset==UTF8){
			//转成json对象
			return JSON.parseObject(bytes,arg0);
		}
		//转成新的编码的json对象
		return JSON.parseObject(bytes,0,bytes.length,
				charset.newDecoder(),arg0);
	}

	@Override
	protected boolean supports(Class<?> arg0) {
		return true;
	}

	@Override
	protected void writeInternal(Object arg0, HttpOutputMessage arg1)
			throws IOException, HttpMessageNotWritableException {
		
		OutputStream out = arg1.getBody();
		byte[] bytes;
		
		if(charset==UTF8){
			if(serializerFeature!=null){
				bytes = JSON.toJSONBytes(arg0, serializerFeature);
			}else{
				bytes = JSON.toJSONBytes(arg0, 
						SerializerFeature.WriteDateUseDateFormat);
			}
		}else{
			String text;
			if(serializerFeature!=null){
				text = JSON.toJSONString(arg0, serializerFeature);
			}else{
				text = JSON.toJSONString(arg0, 
						SerializerFeature.WriteDateUseDateFormat);
			}
			bytes = text.getBytes(charset);
		}
		out.write(bytes);
	}

}
